<?php

namespace Addons\BigWheel\Controller;
use Home\Controller\AddonsController;

class BigWheelController extends AddonsController{
    var $addon = 'BigWheel';
    function edit() {
        $id = I ( 'id' );
        $model = $this->getModel ();

        if (IS_POST) {
            $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
            // 获取模型的字段信息
            $Model = $this->checkAttr ( $Model, $model ['id'] );
            if ($Model->create () && $Model->save ()) {
                $this->_saveKeyword ( $model, $id );

                $this->success ( '保存' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'] ) );
            } else {
                $this->error ( $Model->getError () );
            }
        } else {
            $fields = get_model_attribute ( $model ['id'] );

            // 获取数据
            $data = M ( get_table_name ( $model ['id'] ) )->find ( $id );
            $data || $this->error ( '数据不存在！' );

            $token = get_token ();
            if (isset ( $data ['token'] ) && $token != $data ['token'] && defined ( 'ADDON_PUBLIC_PATH' )) {
                $this->error ( '非法访问！' );
            }

            $this->assign ( 'fields', $fields );
            $this->assign ( 'data', $data );
            $this->meta_title = '编辑' . $model ['title'];

            $this->_deal_data ();

            $this->display ();
        }
    }
    function add() {
        $model = $this->getModel ();
        if (IS_POST) {
            $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
            // 获取模型的字段信息
            $Model = $this->checkAttr ( $Model, $model ['id'] );
            if ($Model->create () && $id = $Model->add ()) {
                $this->_saveKeyword ( $model, $id );

                $this->success ( '添加' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'] ) );
            } else {
                $this->error ( $Model->getError () );
            }
        } else {
            $fields = get_model_attribute ( $model ['id'] );

            $this->assign ( 'fields', $fields );
            $this->meta_title = '新增' . $model ['title'];

            $this->_deal_data ();

            $this->display ();
        }
    }

    // 增加或者编辑时公共部分
    function _deal_data() {
        $normal_tips = '插件场景限制参数说明：格式：[插件名:id],如<br/>
				[投票:10]，表示对ID为10的投票投完对能领取<br/>
				[投票:*]，表示只要投过票就可以领取<br/>
				[微调研:15]，表示完成ID为15的调研就能领取<br/>
				[微考试:10]，表示完成ID为10的考试就能领取<br/>';
        $this->assign ( 'normal_tips', $normal_tips );
    }
    function preview() {
        $this->show ();
    }

    function show() {
        if(isWeixinBrowser()){
            $id = $map ['target_id'] = I ( 'id' );
            $data = M ( 'bigwheel' )->find ( $id );
            $data = $this->max_count($data, $id);

            $this->assign ( 'data', $data );
            $link = GetCurUrl();
            $this->assign ( 'link', $link );

            // 奖项
            $map ['addon'] = 'BigWheel';

            $prizes = M ( 'prize' )->field('id, target_id, img, title, name, num')->where ( $map )->order('sort')->select ();
            $this->assign ( 'udprizes', urldecode(json_encode($prizes)) );
            $this->assign ( 'prizes', $prizes );

            foreach($prizes as &$item){
                $item['people'] = array();
            }
            unset($item);
            // 抽奖记录
            $my_count = 0;
            $no_count = 0;
            $new_prizes = array();
            $has = array();
            $my_prizes = array();
            $all_prizes = M ( 'sn_code' )->where ( $map )->order ( 'id desc' )->select ();

            foreach ( $all_prizes as $key => $all ) {
                if ($all ['prize_id'] > 0) {
                    $has [$all ['prize_id']] += 1; // 每个奖项已经中过的次数
                    if(count($new_prizes)<20 && $all['status'] == 1){
                        $new_prizes [] = $all; // 最新中奖记录
                    }
                    if($all['status'] == 1 && $all ['uid'] == $this->mid){
                        $my_prizes [] = $all; // 我的中奖记录
                    }
                    foreach($prizes as &$item){
                        if($all ['prize_id'] == $item['id']){
                            $item['people'][] = $all;
                        }
                    }
                    unset($item);
                } else {
                    $no_count += 1; // 没有中奖的次数
                }

                // 记录我已抽奖的次数
                if($all ['uid'] == $this->mid){
                    $my_count += 1;
                }
            }

            //最新大奖
            $topprizes = array();
            foreach($prizes as $item){
                if(count($topprizes) <5){
                    foreach($item['people'] as $pitem){
                        if(count($topprizes) <5){
                            $topprizes[] = $pitem;
                        }
                        else{
                            break;
                        }
                    }
                }
                else{
                    break;
                }
            }
            $this->assign ( 'topprizes', $topprizes );

            // 获取我的抽奖机会
            $prize = array ();
            $max_num = empty ( $data ['max_num'] ) ? 1 : $data ['max_num'];
            if (empty ( $data ['max_num'] )) {
                $prize ['count'] = 1;
            } else {
                $prize ['count'] = $max_num - $my_count;
                $prize ['count'] < 0 && $prize ['count'] = 0;
            }
            $this->assign ( 'prize', $prize );

            $this->assign ( 'new_prizes', $new_prizes );
            $this->assign ( 'my_prizes', $my_prizes );
            $this->assign ( 'target_id', $id );

            $this->display ( 'show' );
        }
        else{
            $this->ajaxReturn(array('msg'=>'请使用微信浏览器打开'));
        }
    }

    // 抽奖算法 中奖概率 = 奖品总数/(预估活动人数*每人抽奖次数)
    function _lottery($data, $prizes, $my_count = 0, $has = array(), $no_count = 0) {
        $max_num = empty ( $data ['max_num'] ) ? 1 : $data ['max_num'];
        $count = $data ['predict_num'] * ($data['normal_num'] + $data['follow_num'] + $data['vip_num']); // 总基数
        $rand = array();
        $prizesArr = array();
        // 获取已经中过的奖
        foreach ( $prizes as $p ) {
            $prizesArr [$p ['id']] = $p;

            $prize_num = $p ['num'] - $has [$p ['id']];
            for($i = 0; $i < $prize_num; $i ++) {
                $rand [] = $p ['id']; // 中奖的记录，同时通过ID可以知道中的是哪个奖
            }
        }
        // dump ( $rand );
        // dump ( $prizesArr );

        if ($data ['predict_num'] != 1) {
            $remain = $count - count ( $rand ) - $no_count;
            $remain > 200000 && $remain = 200000; // 防止数组过大导致内存溢出
            for($i = 0; $i < $remain; $i ++) {
                $rand [] = 0; // 不中奖的记录
            }
        }
        if (empty ( $rand )) {
            $rand [] = - 1;
        }

        shuffle ( $rand ); // 所有记录随机排序
        $prize_id = $rand [0]; // 第一个记录作为当前用户的中奖记录
        $prize = array ();

        if ($prize_id > 0) {
            $prize = $prizesArr [$prize_id];
        } else if ($prize_id == - 1) {
            $prize ['id'] = 0;

            $prize ['title'] = '奖品已抽完';
        } else {
            $prize ['id'] = 0;
            $prize ['title'] = '谢谢参与';
        }

        // 获取我的抽奖机会
        if (empty ( $data ['max_num'] )) {
            $prize ['count'] = 1;
        } else {
            $prize ['count'] = $max_num - $my_count - 1;
            $prize ['count'] < 0 && $prize ['count'] = 0;
        }
        return $prize;
    }

    /*抽奖*/
    function play(){
        $id = I ( 'id' );
        $data = M ( 'bigwheel' )->find ( $id );
        $data = $this->max_count($data, $id);

        $map ['token'] = get_token ();
        $map ['openid'] = get_openid ();
        $follow = M ( 'follow' )->where ( $map )->find ();
        $is_admin = is_login ();

        unset($map);
        $map ['target_id'] = I ( 'id' );
        $map ['addon'] = $this->addon;
        $prizes = M ( 'prize' )->field('id, target_id, img, title, name, num')->where ( $map )->select ();
        $my_count = 0;
        $no_count = 0;
        $has = array();
        $all_prizes = M ( 'sn_code' )->where ( $map )->order ( 'id desc' )->select ();
        foreach ( $all_prizes as $key => $all ) {
            if ($all ['prize_id'] > 0) {
                $has [$all ['prize_id']] += 1; // 每个奖项已经中过的次数
            } else {
                $no_count += 1; // 没有中奖的次数
            }

            // 记录我已抽奖的次数
            if($all ['uid'] == $this->mid){
                $my_count += 1;
            }
        }
        $error = '';
        if($data ['start_time'] > time ()){
            $error = '活动未开始';
        } else if ($data ['end_time'] <= time ()) {
            $error = '活动已结束';
        } else if ($data ['max_num'] > 0 && $data ['max_num'] <= $my_count) {
            $error = '您的抽奖机会已用完啦';
        } else if ($data ['credit_conditon'] > intval ( $follow ['score'] ) && ! $is_admin) {
            $error = '您的微币不足';
        } else if ($data ['credit_bug'] > intval ( $follow ['score'] ) && ! $is_admin) {
            $error = '您的微币不够扣除';
        } else if (! empty ( $data ['addon_condition'] )) {
            addon_condition_check ( $data ['addon_condition'] ) || $error = '您没权限参与';
        }
        // 抽奖算法
        if($error == ''){
            $backprize = $this->_lottery ( $data, $prizes, $my_count, $has, $no_count );
            $res = $this->set_sn_code($id, $backprize);
            $this->ajaxReturn(array('statu'=>0, 'content'=>$res));
        }
        else{
            $this->ajaxReturn(array('statu'=>1, 'content'=>$error));
        }
    }

    /*统计总抽奖次数*/
    function max_count($data, $id){
        //统计可抽奖次数
        $followmap ['token'] = get_token ();
        $followmap ['openid'] = get_openid ();
        $follow = M ( 'follow' )->where ( $followmap )->find ();
        $data['max_num'] = $data['normal_num'];
        if($data['follow_num'] > 0 && $follow){
            $data['max_num'] += $data['follow_num'];
        }
        if($data['vip_num'] > 0 && $follow){
            $member = M('card_member')->where(array('uid'=>$follow['id']))->find();
            if($member){
                $data['max_num'] += $data['vip_num'];
            }
        }
        if($data['share_num'] > 0){
            $sharemap['token'] = get_token();
            $sharemap['openid'] = get_openid();
            $sharemap['target_id'] = $id;
            $sharemap['addon'] = $this->addon;
            $sharecount = M('share_log')->where($sharemap)->count();
            if($sharecount<=$data['share_num']){
                $data['max_num'] = $data['max_num'] + $sharecount;
            }
            else{
                $data['max_num'] = $data['max_num'] + $data['share_num'];
            }
        }
        return $data;
    }

    // 记录中奖数据到数据库
    private function set_sn_code($targetid, $prize) {
        $data ['sn'] = uniqid ();
        $data ['uid'] = $this->mid;
        $data ['cTime'] = time ();
        $data ['addon'] = 'BigWheel';
        $data ['target_id'] = $targetid;
        $data ['token'] = get_token();

        $data ['prize_id'] = $map ['id'] = $prize['id'];
        if($prize['id'] > 0){
            $data ['prize_title'] = $prize['title'];
        }

        $res = M ( 'sn_code' )->add ( $data );
        if($res){
            return $prize;
        }
        else{
            $prize['id'] = 0;
            $prize['title'] = '保存失败';
            return $prize;
        }
    }

    //分享链接
    function successtoshare(){
        $sharetype = I('sharetype');
        if($sharetype == 'tofriends'){
            $data['target_id'] = $data1['target_id'] = intval(I('target_id'));
            $data['addon'] = $data1['addon'] = $this->addon;
            $data['openid'] = $data1['openid'] = get_openid();
            $data['token'] = $data1['token'] = get_token();
            $data['cTime'] = time();
            $res = M('share_log')->add($data);
            if($res){
                $count = M('share_log')->where($data1)->count();
                $sharecount = M('bigwheel')->where(array('id'=>$data['target_id']))->getField('share_num');
                if($count<=$sharecount){
                    $this->ajaxReturn(array('statu'=>1, 'content'=>'分享成功, 抽奖次数 + 1'));
                }
                else{
                    $this->ajaxReturn(array('statu'=>1, 'content'=>'分享成功, 抽奖次数 + 0'));
                }
            }
            else{
                $this->ajaxReturn(array('statu'=>1, 'content'=>'分享成功'));
            }
        }
        else{
            $this->ajaxReturn(array('statu'=>0, 'content'=>'分享朋友圈才能获得奖励'));
        }
    }

    //测试
    function test(){
//        $token = get_token();
//        $access_token = get_access_token();
//        $uid = get_mid();
//        $openid = get_openid();
//        $this->assign('token', $token);
//        $this->assign('access_token', $access_token);
//        $this->assign('uid', $uid);
//        $this->assign('openid', $openid);
//
//        $this->display();
    }
}
